package com.zhouqinuan.spring.cloud.develop.framework.routing.datasource.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import com.zhouqinuan.spring.cloud.develop.framework.routing.datasource.RoutingDataSourceContextHolder;
import com.zhouqinuan.spring.cloud.develop.framework.routing.datasource.annotation.DataSource;

@Aspect
public class RoutingDataSourceAop {
    
    @Pointcut("@annotation(com.zhouqinuan.spring.cloud.develop.framework.routing.datasource.annotation.DataSource)")
    public void pointcut() {}
    
    @Around("pointcut()")
    public Object selectDataSource(ProceedingJoinPoint pjp) throws Throwable {
        Object object;
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        RoutingDataSourceContextHolder.setDataSourceKey(dataSource.value());

        try {
            object = pjp.proceed();
        } finally {
            RoutingDataSourceContextHolder.clearDataSourceKey();
        }
        
        return object;
    }
}
